#!/usr/bin/python3
# -*- coding: utf-8 -*-
#======================================#
# @Author   : duanqizhong
# @time     : 2022-8-6 17:52
# @file     : __init__.py
# @Software : PyCharm
#======================================#


import datetime
import functools
import json
import logging.config
import os
import sys

import flask
from flask import jsonify
from flask_cors import CORS


# Json 无法解析 datatime 类型的数据，构建 DateEncoder 类解决 datatime 解析问题
from base.func import get_yaml_dict
from business.order.mock.settings import Port, BASE_DIR, Host


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)

json.dumps = functools.partial(json.dumps, cls=DateEncoder)

# 自定义log
path_log=os.path.join(BASE_DIR,"business/order/config/log.yaml").replace("\\","/")
logging.config.dictConfig(get_yaml_dict(path_log))
if sys.platform.startswith("win"):
    log = logging.getLogger("order_console")
else:
    log = logging.getLogger("order_log")



def create_app(config=None):
    app = flask.Flask(__name__)
    # 支持全局跨域
    CORS(app)
    # load default configuration
    app.config.from_object('business.order.mock.src.settings')
    # load environment configuration
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')
    # load apps sepcified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    @app.route("/health")
    def health():
        return jsonify("I am mock server, Are you ready?")

    return app


if __name__ == '__main__':
    app = create_app()
    app.run(host=Host, port=Port)